package structure;

/**
 * 二叉搜索树
 */
public class BinaryTree {

    private TreeNode root;
    private int size;

    public BinaryTree() {
    }

    public TreeNode getRoot() {
        return root;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }

    /**
     * 动态创建二叉树
     * @param value
     */
    public void createTree(int value){
        TreeNode newTreeNode = new TreeNode(value);
        if(root == null){
            root = newTreeNode;
        }else{
            TreeNode tempNode = root;
            while (tempNode != null){
                if(value > tempNode.getValue()){
                    if(tempNode.getRightChild() == null){
                        tempNode.setRightChild(newTreeNode);
                        return;
                    }else{
                        tempNode = tempNode.getRightChild();
                    }
                } else{
                    if(tempNode.getLeftChild() == null){
                        tempNode.setLeftChild(newTreeNode);
                        return;
                    }else{
                        tempNode = tempNode.getLeftChild();
                    }
                }
            }
        }
    }


    /**
     * 先序遍历
     * @param treeNode
     */
    public void firstTraverseBTree(TreeNode treeNode){
        if ( treeNode != null){
            System.out.println(""+treeNode.getValue());

            firstTraverseBTree(treeNode.getLeftChild());
            firstTraverseBTree(treeNode.getRightChild());
        }
    }

    /**
     * 中序遍历
     * @param treeNode
     */
    public void midTraverseBtrr(TreeNode treeNode){
        if ( treeNode != null){
            firstTraverseBTree(treeNode.getLeftChild());

            System.out.println(""+treeNode.getValue());

            firstTraverseBTree(treeNode.getRightChild());
        }
    }

    /**
     * 后序遍历
     * @param treeNode
     */
    public void lastTraverseBtrr(TreeNode treeNode){
        if ( treeNode != null){
            firstTraverseBTree(treeNode.getLeftChild());
            firstTraverseBTree(treeNode.getRightChild());
            System.out.println(""+treeNode.getValue());
        }
    }
}

